<template>
  <el-form :model="ruleForm" ref="ruleForm" :rules="rules">
    <el-form-item label="原密码" prop="originalPassword">
      <el-input type="password" v-model.trim="ruleForm.originalPassword" />
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <el-input type="password" v-model.trim="ruleForm.newPassword" />
    </el-form-item>
    <el-form-item label="确认新密码" prop="newPasswordConfirm">
      <el-input type="password" v-model.trim="ruleForm.newPasswordConfirm" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">确认修改</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { editPassword } from "@/api/user";
export default {
  props: {
    user: {
      type: Object,
      default: () => {
        return {
          name: "",
          email: "",
        };
      },
    },
  },
  data() {
    return {
      ruleForm: {
        newPassword: "",
        originalPassword: "",
        newPasswordConfirm: "",
      },
      rules: {
        newPassword: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          { min: 6, max: 20, message: "请输入6-20位字符", trigger: "blur" },
        ],
        originalPassword: [
          { required: true, message: "请输入原密码", trigger: "blur" },
          { min: 6, max: 20, message: "请输入6-20位字符", trigger: "blur" },
        ],
        newPasswordConfirm: [
          { required: true, message: "请再次输入新密码", trigger: "blur" },
          { min: 6, max: 20, message: "请输入6-20位字符", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    submit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          if (this.ruleForm.originalPassword == this.ruleForm.newPassword) {
            this.$message({
              message: "原密码不能和新密码相同",
              type: "warning",
            });
          } else if (
            this.ruleForm.newPasswordConfirm != this.ruleForm.newPassword
          ) {
            this.$message({
              message: "新密码输入不一致",
              type: "warning",
            });
          } else {
            if (this.user.name) {
              editPassword({
                newPassword: this.ruleForm.newPassword,
                originalPassword: this.ruleForm.originalPassword,
              }).then((res) => {
                this.$message({
                  message: "新密码设置成功",
                  type: "success",
                });
                this.ruleForm.newPassword = "";
                this.ruleForm.originalPassword = "";
                this.ruleForm.newPassword = "";
                this.logout();
              });
            }
          }
        } else {
          return false;
        }
      });
    },
    async logout() {
      await this.$store.dispatch("user/logout");
      this.$router.push(`/login`);
    },
  },
};
</script>
